package com.ebor.utils.config;

import com.ebor.utils.utils.RequestUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author C
 */
@Aspect
@Component
@Slf4j
@NoArgsConstructor
public class WebLogAspect {

    /**
     * 定义请求日志切入点，其切入点表达式有多种匹配方式,这里是指定路径
     */
    @Pointcut("execution(public * com.ebor.utils.controller..*.*(..))")
    public void webLogPointcut() {
    }


    /**
     * 正确响应时日志
     *
     * @param res 响应结果
     */
    @AfterReturning(returning = "res", pointcut = "webLogPointcut()")
    public void doAfterReturning(Object res) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(Objects.isNull(attributes)) {
            log.error("记录日志时getRequestAttributes()为空");
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        log.info("\nURL:{}\nHeaders:{}\nHTTP-Method:{}\nIP:{}\nparams:{}\nresult:{}", request.getRequestURL().toString(),
                RequestUtils.getHeaders(request), request.getMethod(), request.getRemoteAddr(), RequestUtils.getParameter(request),
                JSONObject.toJSON(res));

    }
}
